package zeebe.awaitWorkflowResult;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.zeebe.client.ZeebeClient;
import io.zeebe.client.api.response.WorkflowInstanceResult;

public class AwaitWorkflowResultVertx extends AbstractVerticle {

    @Override
    public void start(Promise<Void> startPromise) {
        ZeebeClient client = ZeebeClient.newClientBuilder()
                .brokerContactPoint("localhost:26500")
                .usePlaintext()
                .build();

        String bpmnPath = "bpmn/awaitWorkflowResult.bpmn";
        client.newDeployCommand()
                .addResourceFromClasspath(bpmnPath)
                .send()
                .join();

        String inputType = "plus";
        PlusJobWorkerHandler plusJobWorkerHandler = new PlusJobWorkerHandler(client);
        client.newWorker()
                .jobType(inputType)
                .handler(plusJobWorkerHandler)
                .open();

        vertx.createHttpServer()
                .requestHandler(req -> {
                    String processId = "awaitWorkflowResult";
                    JsonObject data = new JsonObject()
                            .put("a", 1)
                            .put("b", 2);
                    WorkflowInstanceResult workflowInstanceResult = client.newCreateInstanceCommand()
                            .bpmnProcessId(processId)
                            .latestVersion()
                            .variables(data.encode())
                            .withResult()
                            .send()
                            .join();
                    System.out.println("流程结果：" + workflowInstanceResult.getVariables());

                    req.response().end(workflowInstanceResult.getVariables());
                })
                .listen(8888, result -> {
                    if (result.succeeded()) {
                        startPromise.complete();
                    } else {
                        startPromise.fail(result.cause());
                    }
                });


    }

}
